package com.internetCafes.spms.common.module.mybatis.plugin;

import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import java.util.Properties;



@Intercepts({
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class,RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}),
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class,Object.class})})
public class EmptyCollectionInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        //通过invocation.getArgs()可以得到当前执行方法的参数
        //第一个args[0]是MappedStatement对象，第二个args[1]是参数对象parameterObject。
        final Object[] args = invocation.getArgs();
        MappedStatement mappedStatement = (MappedStatement) args[0];
        Object parameter = args[1];
        if (parameter == null) {
            Class parameterType = mappedStatement.getParameterMap().getType();
            // 实际执行时的参数值为空，但mapper语句上存在输入参数的异常状况，返回默认值
            if (parameterType != null) {
                return SqlParserUtils.getDefaultReturnValue(invocation);
            }
            return invocation.proceed();
        }
        BoundSql boundSql = mappedStatement.getBoundSql(parameter);
        if (SqlParserUtils.isHaveEmptyList(boundSql.getSql())) {
            return SqlParserUtils.getDefaultReturnValue(invocation);
        }
        return invocation.proceed();
    }



    @Override
    public Object plugin(Object target) {
        //只拦截Executor对象，减少目标被代理的次数
        if (target instanceof Executor) {
            return Plugin.wrap(target, this);
        } else {
            return target;
        }
    }



    @Override
    public void setProperties(Properties properties) {

    }
}
